import web
import view,config
from view import render
import MySQLdb
import json

urls = (
    '/list.json', 'list',
    '/update', 'update'
    )

limit = 54 

def opendb():
    db=MySQLdb.connect(host='localhost', db='xdouban', user='root', passwd='justsoso123', use_unicode=True)
    db.set_character_set('utf8')
    return db

def closedb(db):
    db.close()    

class list:
    def GET(self):
        db = opendb() 
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        """cursor.execute("select id,uid,href,cover from user_albums order by id asc limit 2000")
        """
        cursor.execute("select id, cover_img as cover, album_id from album where checked=0 order by id asc limit %d" % limit )
        albums = cursor.fetchall()
        cursor.close()
        closedb(db)
        return json.dumps(albums) 

class update:
    def POST(self):
        user_data = web.input(album=[])
        db = opendb() 
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        if len(user_data.album)>0:
            cursor.execute("update album set selected=1 where id in (%s)" % ','.join(user_data.album) )
        cursor.execute("update album set checked=1 where id>=%d and id<=%d" % (int(user_data.min_id),int(user_data.max_id)) )
        cursor.close()
        closedb(db)
        return "OK"


if __name__ == "__main__":
    app = web.application(urls, globals())
    app.internalerror = web.debugerror
    app.run()
